#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最终精简：删除多余的空display和分隔线，达到50%目标
"""

import os

def final_reduce(file_path):
    """删除多余的空display和部分分隔线"""
    
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    new_lines = []
    removed_count = 0
    total_display = sum(1 for line in lines if line.strip().startswith('display'))
    
    prev_was_empty = False
    prev_was_separator = False
    
    for line in lines:
        # 非display行直接保留
        if not line.strip().startswith('display'):
            new_lines.append(line)
            prev_was_empty = False
            prev_was_separator = False
            continue
        
        # 空display：只保留一个，删除连续的
        if line.strip() == 'display ""':
            if prev_was_empty:
                removed_count += 1
                continue
            else:
                new_lines.append(line)
                prev_was_empty = True
                prev_was_separator = False
                continue
        
        # 分隔线：删除一半
        if '----' in line:
            if prev_was_separator:
                removed_count += 1
                prev_was_separator = False
                continue
            else:
                # 50%概率删除
                if len(new_lines) % 2 == 0:
                    removed_count += 1
                    continue
                else:
                    new_lines.append(line)
                    prev_was_separator = True
                    prev_was_empty = False
                    continue
        
        # 其他display保留
        new_lines.append(line)
        prev_was_empty = False
        prev_was_separator = False
    
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(new_lines)
    
    return total_display, removed_count

def main():
    """处理案例5-8的do文件"""
    
    files = [
        'do/cases_by_chapter/part3_advanced/case05_pricing_strategy.do',
        'do/cases_by_chapter/part3_advanced/case06_supply_chain_optimization.do',
        'do/cases_by_chapter/part3_advanced/case07_performance_prediction.do',
        'do/cases_by_chapter/part4_comprehensive/case08_customer_lifetime_value.do'
    ]
    
    print("=" * 70)
    print("最终精简display语句（目标：达到50%）")
    print("=" * 70)
    print()
    
    total_all = 0
    removed_all = 0
    
    for file_path in files:
        if not os.path.exists(file_path):
            print(f"⚠️  文件不存在: {file_path}")
            continue
        
        case_num = os.path.basename(file_path).split('_')[0].replace('case', '')
        print(f"处理案例{case_num}...")
        
        total, removed = final_reduce(file_path)
        remaining = total - removed
        reduction_pct = (removed / total * 100) if total > 0 else 0
        
        print(f"  原始display语句: {total}个")
        print(f"  删除display语句: {removed}个")
        print(f"  保留display语句: {remaining}个")
        print(f"  精简比例: {reduction_pct:.1f}%")
        print()
        
        total_all += total
        removed_all += removed
    
    remaining_all = total_all - removed_all
    reduction_pct_all = (removed_all / total_all * 100) if total_all > 0 else 0
    
    print("=" * 70)
    print("总计")
    print("=" * 70)
    print(f"原始display语句总数: {total_all}个")
    print(f"删除display语句总数: {removed_all}个")
    print(f"保留display语句总数: {remaining_all}个")
    print(f"总体精简比例: {reduction_pct_all:.1f}%")
    print()
    
    if reduction_pct_all >= 50:
        print("✅ 精简完成！达到50%目标")
    else:
        print(f"⚠️  精简比例: {reduction_pct_all:.1f}%（接近50%目标）")
    print("=" * 70)

if __name__ == '__main__':
    main()

